# -*- coding: utf-8 -*-
"""场景管理相关路由"""

from flask import Blueprint, jsonify, request
from video_processing.scene_manager import get_scene_manager
import logging

logger = logging.getLogger(__name__)

# 创建场景管理蓝图
scenes_bp = Blueprint('scenes', __name__, url_prefix='/scenes')


@scenes_bp.route('/', methods=['GET'])
def get_scenes():
    """
    获取所有场景列表
    """
    try:
        scene_manager = get_scene_manager()
        scenes = scene_manager.list_scenes()
        
        # 转换为字典格式并添加活动状态
        scenes_data = []
        active_scene_id = scene_manager.active_scene_id
        for scene in scenes:
            scene_dict = scene.to_dict()
            scene_dict['active'] = scene.scene_id == active_scene_id
            scenes_data.append(scene_dict)
        
        return jsonify({
            'success': True,
            'scenes': scenes_data,
            'message': '获取场景列表成功'
        }), 200
    except Exception as e:
        logger.error(f"获取场景列表失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'获取场景列表失败: {str(e)}'
        }), 500


@scenes_bp.route('/', methods=['POST'])
def create_scene():
    """
    创建新场景
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                'success': False,
                'message': '请求数据不能为空'
            }), 400
        
        scene_id = data.get('scene_id')
        name = data.get('name')
        description = data.get('description', '')
        
        if not scene_id or not name:
            return jsonify({
                'success': False,
                'message': '场景ID和场景名称不能为空'
            }), 400
        
        scene_manager = get_scene_manager()
        scene = scene_manager.create_scene(scene_id, name, description)
        
        return jsonify({
            'success': True,
            'scene': scene.to_dict(),
            'message': '场景创建成功'
        }), 201
    except Exception as e:
        logger.error(f"创建场景失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'创建场景失败: {str(e)}'
        }), 500


@scenes_bp.route('/<scene_id>', methods=['GET'])
def get_scene(scene_id):
    """
    获取指定场景信息
    """
    try:
        scene_manager = get_scene_manager()
        scene = scene_manager.get_scene(scene_id)
        
        if not scene:
            return jsonify({
                'success': False,
                'message': '场景不存在'
            }), 404
        
        scene_dict = scene.to_dict()
        scene_dict['active'] = scene_id == scene_manager.active_scene_id
        
        return jsonify({
            'success': True,
            'scene': scene_dict,
            'message': '获取场景信息成功'
        }), 200
    except Exception as e:
        logger.error(f"获取场景信息失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'获取场景信息失败: {str(e)}'
        }), 500


@scenes_bp.route('/<scene_id>', methods=['PUT'])
def update_scene(scene_id):
    """
    更新场景信息
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                'success': False,
                'message': '请求数据不能为空'
            }), 400
        
        # 移除scene_id字段，避免修改
        if 'scene_id' in data:
            del data['scene_id']
        
        scene_manager = get_scene_manager()
        scene = scene_manager.update_scene(scene_id, **data)
        
        if not scene:
            return jsonify({
                'success': False,
                'message': '场景不存在'
            }), 404
        
        return jsonify({
            'success': True,
            'scene': scene.to_dict(),
            'message': '场景更新成功'
        }), 200
    except Exception as e:
        logger.error(f"更新场景失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'更新场景失败: {str(e)}'
        }), 500


@scenes_bp.route('/<scene_id>', methods=['DELETE'])
def delete_scene(scene_id):
    """
    删除场景
    """
    try:
        scene_manager = get_scene_manager()
        success = scene_manager.delete_scene(scene_id)
        
        if not success:
            return jsonify({
                'success': False,
                'message': '场景不存在'
            }), 404
        
        return jsonify({
            'success': True,
            'message': '场景删除成功'
        }), 200
    except Exception as e:
        logger.error(f"删除场景失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'删除场景失败: {str(e)}'
        }), 500


@scenes_bp.route('/<scene_id>/activate', methods=['POST'])
def activate_scene(scene_id):
    """
    激活指定场景
    """
    try:
        scene_manager = get_scene_manager()
        success = scene_manager.switch_to_scene(scene_id)
        
        if not success:
            return jsonify({
                'success': False,
                'message': '场景不存在'
            }), 404
        
        return jsonify({
            'success': True,
            'message': '场景激活成功'
        }), 200
    except Exception as e:
        logger.error(f"激活场景失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'激活场景失败: {str(e)}'
        }), 500


@scenes_bp.route('/deactivate', methods=['POST'])
def deactivate_scene():
    """
    取消激活所有场景
    """
    try:
        scene_manager = get_scene_manager()
        scene_manager.switch_to_scene(None)
        
        return jsonify({
            'success': True,
            'message': '场景已取消激活'
        }), 200
    except Exception as e:
        logger.error(f"取消激活场景失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'取消激活场景失败: {str(e)}'
        }), 500


@scenes_bp.route('/active', methods=['GET'])
def get_active_scene():
    """
    获取当前活动场景
    """
    try:
        scene_manager = get_scene_manager()
        active_scene = scene_manager.get_active_scene()
        
        if active_scene:
            scene_dict = active_scene.to_dict()
            scene_dict['active'] = True
            return jsonify({
                'success': True,
                'scene': scene_dict,
                'message': '获取活动场景成功'
            }), 200
        else:
            return jsonify({
                'success': True,
                'scene': None,
                'message': '当前没有活动场景'
            }), 200
    except Exception as e:
        logger.error(f"获取活动场景失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'获取活动场景失败: {str(e)}'
        }), 500


@scenes_bp.route('/stats', methods=['GET'])
def get_scene_stats():
    """
    获取场景统计信息
    """
    try:
        scene_manager = get_scene_manager()
        return jsonify({
            'success': True,
            'stats': scene_manager.stats,
            'message': '获取场景统计信息成功'
        }), 200
    except Exception as e:
        logger.error(f"获取场景统计信息失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'获取场景统计信息失败: {str(e)}'
        }), 500